package initialize

import (
	"bookProjectSrv/global"
	"bookProjectSrv/vender/consul"
	"fmt"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	uuid "github.com/satori/go.uuid"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gopkg.in/yaml.v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

func init() {
	InitConfig()       //配置文件
	InitalizeLoggeer() //日志包
	InitConsul()       //consul
	InitDB()           //初始化数据库配置
}

func InitConfig() {
	//默认加载配置项  以全局变量的形式输出
	//初始化
	v := viper.New()
	//设置配置文件
	v.SetConfigFile("./application-dev.yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	NacosConfig := global.NacosConfig{}
	//读取的时候层级关系对应
	if err := v.Unmarshal(&NacosConfig); err != nil {
		panic(err)
	}
	global.NacosServer = &NacosConfig

	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "", // 如果需要支持多namespace，我们可以创建多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: global.NacosServer.Host,
			Port:   global.NacosServer.Port,
		},
	}

	// 创建动态配置客户端
	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	//获取配置：GetConfig
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosServer.DataId,
		Group:  global.NacosServer.Group})
	if err != nil {
		panic(err)
	}
	//json转译  映射到结构体
	ServerConfig := global.ServerConfig{}
	//想要将一个json字符串转换成struct，需要去设置这个struct的tag
	yaml.Unmarshal([]byte(content), &ServerConfig)
	global.GlobalConfig = &ServerConfig
}

func InitalizeLoggeer() {
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		//global.GlobalConfig.Service.LogPath,
		"stderr",
		"stdout",
	}
	//构建并初始化
	logger, _ := config.Build()
	//替换为全局变量
	zap.ReplaceGlobals(logger)
}

// 初始化数据库
func InitDB() {
	m := global.GlobalConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		m.User, m.Pwd, m.Host, m.Port, m.DbName)
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,   // 慢 SQL 阈值
			LogLevel:      logger.Silent, // Log level
			Colorful:      false,         // 禁用彩色打印
		},
	)
	// 全局模式
	var err error
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		//NamingStrategy: schema.NamingStrategy{
		//	//SingularTable: true,
		//},
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}
	zap.S().Infow("数据库初始化成功", zap.Int("code", 200))
}

func InitConsul() {
	//初始化配置
	config := api.DefaultConfig()
	//通过配置进行实例化
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	global.ConsuleClient = client
	//实例化consul调用类
	consulClient := consul.NewRegistryClient(global.GlobalConfig.Consule.Host, global.GlobalConfig.Consule.Port)
	serviceId := uuid.NewV4().String()
	//调用服务过滤接口
	filterResult := consulClient.FilterService(global.GlobalConfig.Consule.Name)
	BaseSrvIp := ""
	for _, value := range filterResult {
		BaseSrvIp = value.Address
		break
	}
	if BaseSrvIp == "" {
		err = consulClient.RegisterConsul(global.GlobalConfig.Consule.Name, global.GlobalConfig.Consule.Port, global.GlobalConfig.Consule.Name, global.GlobalConfig.Consule.Tag, serviceId)
		if err != nil {
			panic(err)
			zap.S().Panic("服务注册失败:", err.Error())
		}
	} else {
		zap.S().Info("服务已经注册，无需再次注册")
	}

}
